package com.zd.springsecuritydemo.response;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.zd.springsecuritydemo.pojo.entity.User;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZhangDong
 * @date 2024/1/7 12:59
 */
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;
    // 存储权限信息
    private List<String> permissions;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setId(1L);
        ArrayList<String> objects = new ArrayList<>();
        objects.add("test");
        LoginUser loginUser = new LoginUser(user, objects);
        System.err.println(JSON.toJSONString(loginUser));
    }

    // 不参与redis 序列化
    // 新增它的目的是为了降低多次调用getAuthorities的性能损耗（毕竟原先每次都要new 对象）
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorityList;

    @Override
    @JSONField(serialize = false)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorityList != null) {
            return authorityList;
        }
        authorityList = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorityList;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    @JSONField(serialize = false)
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JSONField(serialize = false)
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JSONField(serialize = false)
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JSONField(serialize = false)
    public boolean isEnabled() {
        return true;
    }
}
